package com.bxait;

import com.bxait.utils.ESClientSingle;
import com.bxait.utils.User;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.elasticsearch.action.DocWriteResponse;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;

import java.io.IOException;

/**
 * @author Chen
 * @description: es批量插入数据
 * @ClassName ESTest_Client
 * @create 2023-04-08 16:16
 * @Version 1.0
 */
public class ESTest_Doc_Insert_Batch {

    public static void main(String[] args) throws IOException {
        // 创建ES的客户端
        RestHighLevelClient client = ESClientSingle.getInstant();

        // 批量插入数据
        BulkRequest request = new BulkRequest();
        ObjectMapper mapper = new ObjectMapper();
        String userJson1 = mapper.writeValueAsString(new User("zhangSan","男",20));
        String userJson2 = mapper.writeValueAsString(new User("liSi","男",20));
        String userJson3 = mapper.writeValueAsString(new User("chen","男",20));
        String userJson4 = mapper.writeValueAsString(new User("jia","男",20));
        String userJson5 = mapper.writeValueAsString(new User("hui","男",20));
        String userJson6 = mapper.writeValueAsString(new User("tang","男",20));
        request.add(new IndexRequest().index("user").id("1001").source(userJson1,XContentType.JSON));
        request.add(new IndexRequest().index("user").id("1002").source(userJson2,XContentType.JSON));
        request.add(new IndexRequest().index("user").id("1003").source(userJson3,XContentType.JSON));
        request.add(new IndexRequest().index("user").id("1004").source(userJson4,XContentType.JSON));
        request.add(new IndexRequest().index("user").id("1005").source(userJson5,XContentType.JSON));
        request.add(new IndexRequest().index("user").id("1006").source(userJson6,XContentType.JSON));
        BulkResponse response = client.bulk(request, RequestOptions.DEFAULT);
        System.out.println(response.getTook());
        System.out.println(response.getItems());
        // 关闭es客户端
        client.close();
    }

}
